const Chat = require('../models/Chat');
const User = require('../models/User');
const Post = require('../models/Post');
const Friend = require('../models/Friend');

// 发送消息
exports.sendMessage = async (req, res) => {
  const { receiverId, message } = req.body;
  const senderId = req.user._id;

  try {
    // 验证是否为好友
    const isFriend = await Friend.findOne({
      $or: [
        { user1: senderId, user2: receiverId, status: 'accepted' },
        { user1: receiverId, user2: senderId, status: 'accepted' }
      ]
    });

    // 如果不是好友，仍然允许发送消息，但标记为临时聊天
    const chat = new Chat({
      sender: senderId,
      receiver: receiverId,
      message,
      type: 'text',
      isTemporary: !isFriend // 添加临时聊天标记
    });
    await chat.save();
    res.status(201).json(chat);
  } catch (error) {
    res.status(500).json({ message: 'Error sending message', error });
  }
};

// 发送帖子
exports.sendPost = async (req, res) => {
  const { receiverId, postId } = req.body;
  const senderId = req.user._id;

  try {
    // 验证是否为好友
    const isFriend = await Friend.findOne({
      $or: [
        { user1: senderId, user2: receiverId, status: 'accepted' },
        { user1: receiverId, user2: senderId, status: 'accepted' }
      ]
    });

    if (!isFriend) {
      return res.status(403).json({ message: 'You can only send posts to friends' });
    }

    const post = await Post.findById(postId);
    if (!post) {
      return res.status(404).json({ message: 'Post not found' });
    }

    const chat = new Chat({
      sender: senderId,
      receiver: receiverId,
      message: post.content,
      type: 'post',
      postId
    });
    await chat.save();
    res.status(201).json(chat);
  } catch (error) {
    res.status(500).json({ message: 'Error sending post', error });
  }
};

// 发送表情
exports.sendEmoji = async (req, res) => {
  const { receiverId, emoji } = req.body;
  const senderId = req.user._id;

  try {
    const chat = new Chat({
      sender: senderId,
      receiver: receiverId,
      message: emoji,
      type: 'emoji'
    });
    await chat.save();
    res.status(201).json(chat);
  } catch (error) {
    res.status(500).json({ message: 'Error sending emoji', error });
  }
};

// 获取聊天历史
exports.getChatHistory = async (req, res) => {
  const userId = req.params.userId;
  const senderId = req.user._id;

  try {
    const chats = await Chat.find({
      $or: [
        { sender: senderId, receiver: userId },
        { sender: userId, receiver: senderId }
      ]
    }).sort({ createdAt: 1 });
    res.status(200).json(chats);
  } catch (error) {
    res.status(500).json({ message: 'Error fetching chat history', error });
  }
};